"""
股票资金分析智能体

基于资金流向和成交量分析股票资金动向。
支持文本和JSON格式输出。
"""

from typing import Dict, Any, List, Optional, Union
from agents import BaseAgent, LLMConfig
from tools.stock_data_provider import stock_data_provider
from langchain_core.tools import Tool
import pandas as pd
import logging


class StockCapitalFlowAnalysisAgent(BaseAgent):
    """股票资金分析智能体"""

    def __init__(self, llm_config: Optional[LLMConfig] = None):
        super().__init__(
            name="StockCapitalFlowAnalysisAgent",
            description="股票资金分析智能体，基于资金流向进行分析",
            llm_config=llm_config
        )
        self.logger = logging.getLogger(__name__)

    def get_tools(self) -> List[Tool]:
        """获取资金分析所需的工具"""
        return [
            Tool(
                name="get_capital_flow_data",
                description="获取股票实时资金流向数据，包括主力资金、散户资金流入流出情况",
                func=self._get_capital_flow_data
            ),
            Tool(
                name="analyze_volume_trends",
                description="获取历史成交数据并分析成交量趋势和量价关系",
                func=self._analyze_volume_trends
            ),
            Tool(
                name="assess_institutional_involvement",
                description="获取资金流向数据并评估机构参与度和主力行为",
                func=self._assess_institutional_involvement
            ),
            Tool(
                name="analyze_market_sentiment",
                description="获取资金和成交数据并分析市场情绪和投资者行为",
                func=self._analyze_market_sentiment
            ),
            Tool(
                name="generate_capital_signals",
                description="综合获取资金数据并生成投资信号和建议",
                func=self._generate_capital_signals
            )
        ]

    def get_system_prompt(self) -> str:
        return """
        你是专业的股票资金分析智能体，基于资金流向和成交量分析市场动向。

        分析框架：
        1. 资金流向解析：主力资金、散户资金动向
        2. 成交量趋势：成交量变化和量价关系
        3. 机构参与度：主力行为和机构态度
        4. 市场情绪量化：基于资金数据的市场情绪
        5. 资金信号生成：综合资金面投资建议

        输出结构：
        ## 💹 资金流向
        - 主力资金动向
        - 散户资金行为

        ## 📊 成交量分析
        - 成交量趋势
        - 量价配合度

        ## 🏛️ 机构参与
        - 机构参与度评估
        - 主力行为分析

        ## 🎭 市场情绪
        - 情绪指数量化
        - 市场氛围评估

        ## 🎯 资金信号
        - 主要资金信号
        - 信心指数评分
        - 投资建议

        ## ⭐ 资金面评分 (0-10)
        评分标准：
        - 10: 资金面极佳，主力和散户资金齐聚，成交活跃
        - 8-9: 资金面良好，主力资金积极，市场认可度高
        - 6-7: 资金面平稳，资金流动正常
        - 4-5: 资金面一般，存在一定资金分歧
        - 2-3: 资金面较弱，资金有流出迹象
        - 0-1: 资金面极差，大量资金撤离，市场冷清

        最终评分：[X/10] - 评分理由

        分析原则：
        - 关注大单和小单的资金动向差异
        - 结合价格走势分析资金效率
        - 考虑市场整体资金环境
        - 资金分析具有时效性，需结合最新数据

        请基于数据量化分析，避免主观臆断。
        """

    async def _get_capital_flow_data(self, stock_code: str) -> str:
        """获取资金流向数据"""
        try:
            flow_data = await stock_data_provider.get_stock_capital_flow(stock_code)

            if not flow_data:
                return f"无法获取股票{stock_code}的资金流向数据"

            result = f"股票{stock_code}资金流向分析：\n\n"

            main_inflow = flow_data.get('main_inflow', 0)
            main_inflow_ratio = flow_data.get('main_inflow_ratio', 0)
            retail_inflow = flow_data.get('retail_inflow', 0)
            retail_inflow_ratio = flow_data.get('retail_inflow_ratio', 0)

            result += f"📊 资金流向概况：\n"
            result += f"  主力资金流入: {main_inflow:,.0f}元 ({main_inflow_ratio:.2%})\n"
            result += f"  散户资金流入: {retail_inflow:,.0f}元 ({retail_inflow_ratio:.2%})\n\n"

            # 资金性质判断
            if main_inflow > 0 and main_inflow_ratio > 0.5:
                main_signal = "🔥 主力资金大力流入"
            elif main_inflow > 0:
                main_signal = "📈 主力资金温和流入"
            elif main_inflow < -1000000:  # 大额流出
                main_signal = "❄️ 主力资金大幅流出"
            else:
                main_signal = "📉 主力资金小幅流出"

            if retail_inflow > 0 and retail_inflow_ratio > 0.3:
                retail_signal = "👥 散户资金积极买入"
            elif retail_inflow > 0:
                retail_signal = "🙋 散户资金小幅买入"
            elif retail_inflow < -500000:
                retail_signal = "😰 散户资金抛售离场"
            else:
                retail_signal = "😐 散户资金观望"

            result += f"🎯 资金信号：\n"
            result += f"  {main_signal}\n"
            result += f"  {retail_signal}\n"

            return result

        except Exception as e:
            return f"获取资金流向数据失败: {e}"

    async def _analyze_volume_trends(self, stock_code: str) -> str:
        """分析成交量趋势"""
        try:
            history_data = await stock_data_provider.get_stock_history_data(stock_code)

            if history_data.empty:
                return f"无法获取股票{stock_code}的历史成交数据"

            volumes = history_data['成交量']
            prices = history_data['收盘']

            result = f"股票{stock_code}成交量趋势分析：\n\n"

            # 计算成交量指标
            volume_ma5 = volumes.rolling(5).mean()
            volume_ma20 = volumes.rolling(20).mean()

            # 量价关系分析
            recent_volume = volumes.iloc[-1]
            avg_volume_5 = volume_ma5.iloc[-1]
            avg_volume_20 = volume_ma20.iloc[-1]

            # 成交量等级
            if recent_volume > avg_volume_20 * 2:
                volume_level = "🔥 成交量极度放大"
            elif recent_volume > avg_volume_20 * 1.5:
                volume_level = "📈 成交量显著放大"
            elif recent_volume > avg_volume_5:
                volume_level = "📊 成交量温和放大"
            elif recent_volume < avg_volume_5 * 0.7:
                volume_level = "📉 成交量萎缩"
            else:
                volume_level = "➡️ 成交量平稳"

            result += f"📊 成交量分析：\n"
            result += f"  {volume_level}\n"
            result += f"  当日成交量: {recent_volume:,.0f}\n"
            result += f"  5日均量: {avg_volume_5:,.0f}\n"
            result += f"  20日均量: {avg_volume_20:,.0f}\n\n"

            # 量价配合度
            price_change = (prices.iloc[-1] - prices.iloc[-2]) / prices.iloc[-2]
            volume_change = (recent_volume - volumes.iloc[-2]) / volumes.iloc[-2]

            if price_change > 0.03 and volume_change > 0.5:
                relation = "✅ 价涨量增（强势信号）"
            elif price_change > 0.03 and volume_change < -0.3:
                relation = "⚠️ 价涨量缩（上涨乏力）"
            elif price_change < -0.03 and volume_change > 0.5:
                relation = "❌ 价跌量增（恐慌抛售）"
            elif price_change < -0.03 and volume_change < -0.3:
                relation = "🛡️ 价跌量缩（下跌缩量）"
            else:
                relation = "🤔 量价关系一般"

            result += f"🔄 量价关系: {relation}\n"
            result += f"  股价变化: {price_change:.2%}\n"
            result += f"  成交量变化: {volume_change:.2%}\n"

            return result

        except Exception as e:
            return f"分析成交量趋势失败: {e}"

    async def _assess_institutional_involvement(self, stock_code: str) -> str:
        """评估机构参与度"""
        try:
            flow_data = await stock_data_provider.get_stock_capital_flow(stock_code)

            if not flow_data:
                return f"无法评估股票{stock_code}的机构参与度"

            result = f"股票{stock_code}机构参与度评估：\n\n"

            main_inflow = flow_data.get('main_inflow', 0)
            main_inflow_ratio = flow_data.get('main_inflow_ratio', 0)

            # 机构参与度判断
            if main_inflow_ratio > 0.7:
                involvement = "🏦 机构高度参与（主力主导）"
                confidence = "高"
            elif main_inflow_ratio > 0.4:
                involvement = "🏢 机构积极参与"
                confidence = "中高"
            elif main_inflow_ratio > 0.1:
                involvement = "📊 机构适度参与"
                confidence = "中等"
            elif main_inflow_ratio > -0.1:
                involvement = "🤔 机构观望中"
                confidence = "低"
            else:
                involvement = "🚫 机构撤离中"
                confidence = "极低"

            result += f"🎯 机构参与评估: {involvement}\n"
            result += f"📈 参与度信心: {confidence}\n\n"

            # 机构行为分析
            if main_inflow > 5000000:  # 500万以上
                behavior = "💰 机构大手笔买入"
            elif main_inflow > 1000000:  # 100万以上
                behavior = "📈 机构稳步买入"
            elif main_inflow < -1000000:
                behavior = "📉 机构抛售离场"
            else:
                behavior = "⚖️ 机构调仓换股"

            result += f"🏛️ 机构行为: {behavior}\n"
            result += f"💵 主力资金净额: {main_inflow:,.0f}元\n"

            return result

        except Exception as e:
            return f"评估机构参与度失败: {e}"

    async def _analyze_market_sentiment(self, stock_code: str) -> str:
        """分析市场情绪"""
        try:
            # 获取资金流向和成交量数据
            flow_data = await stock_data_provider.get_stock_capital_flow(stock_code)
            history_data = await stock_data_provider.get_stock_history_data(stock_code)

            if not flow_data or history_data.empty:
                return "数据不足，无法分析市场情绪"

            result = f"股票{stock_code}市场情绪分析：\n\n"

            # 综合资金和成交量分析情绪
            main_inflow_ratio = flow_data.get('main_inflow_ratio', 0)
            retail_inflow_ratio = flow_data.get('retail_inflow_ratio', 0)

            # 成交量相对强度
            volumes = history_data['成交量']
            volume_ma20 = volumes.rolling(20).mean()
            volume_ratio = volumes.iloc[-1] / volume_ma20.iloc[-1] if not volume_ma20.empty else 1

            # 情绪指标计算
            sentiment_score = 0

            # 主力资金情绪
            if main_inflow_ratio > 0.5:
                sentiment_score += 40
            elif main_inflow_ratio > 0.2:
                sentiment_score += 20
            elif main_inflow_ratio < -0.2:
                sentiment_score -= 30

            # 散户资金情绪
            if retail_inflow_ratio > 0.3:
                sentiment_score += 20  # 散户狂热
            elif retail_inflow_ratio < -0.3:
                sentiment_score -= 20  # 散户恐慌

            # 成交量情绪
            if volume_ratio > 2:
                sentiment_score += 30  # 极度活跃
            elif volume_ratio > 1.5:
                sentiment_score += 15  # 较为活跃
            elif volume_ratio < 0.7:
                sentiment_score -= 15  # 较为冷清

            # 情绪判断
            if sentiment_score > 60:
                sentiment = "🔥 市场极度乐观"
                description = "资金疯狂涌入，市场情绪高涨"
            elif sentiment_score > 30:
                sentiment = "😊 市场乐观向上"
                description = "资金积极流入，投资者信心较强"
            elif sentiment_score > -10:
                sentiment = "😐 市场情绪平稳"
                description = "资金流动正常，投资者相对理性"
            elif sentiment_score > -40:
                sentiment = "😟 市场情绪谨慎"
                description = "资金有所流出，投资者开始观望"
            else:
                sentiment = "😱 市场极度悲观"
                description = "资金大幅流出，市场恐慌情绪蔓延"

            result += f"🎭 整体情绪: {sentiment}\n"
            result += f"📊 情绪得分: {sentiment_score:+d}\n"
            result += f"💬 情绪描述: {description}\n\n"

            # 情绪驱动因素
            result += "🔍 情绪驱动因素：\n"
            if main_inflow_ratio > 0.3:
                result += "  ✅ 主力资金积极\n"
            if retail_inflow_ratio > 0.2:
                result += "  ✅ 散户资金热情\n"
            if volume_ratio > 1.8:
                result += "  ✅ 成交量异常活跃\n"
            if main_inflow_ratio < -0.2:
                result += "  ❌ 主力资金撤离\n"
            if retail_inflow_ratio < -0.2:
                result += "  ❌ 散户资金抛售\n"
            if volume_ratio < 0.8:
                result += "  ❌ 成交量明显萎缩\n"

            return result

        except Exception as e:
            return f"分析市场情绪失败: {e}"

    async def generate_capital_flow_charts(self, stock_code: str) -> Dict[str, Any]:
        """生成资金流向可视化图表"""
        try:
            self.logger.info(f"开始生成股票{stock_code}的资金流向图表")
            
            # 获取资金流向数据
            flow_data = await stock_data_provider.get_stock_capital_flow(stock_code)
            history_data = await stock_data_provider.get_stock_history_data(stock_code)
            
            if not flow_data or history_data.empty:
                self.logger.warning(f"股票{stock_code}的资金流向数据不足")
                return {"error": "资金流向数据不足"}
            
            charts = {}
            
            # 生成资金流向堆叠图
            capital_flow_chart = await self._generate_capital_flow_stacked_chart(flow_data, stock_code)
            if capital_flow_chart:
                charts["capital_flow_stacked"] = capital_flow_chart
            
            # 生成净流入趋势图
            net_flow_chart = await self._generate_net_flow_trend_chart(flow_data, history_data, stock_code)
            if net_flow_chart:
                charts["net_flow_trend"] = net_flow_chart
            
            # 生成成交量资金关系图
            volume_flow_chart = await self._generate_volume_flow_relation_chart(flow_data, history_data, stock_code)
            if volume_flow_chart:
                charts["volume_flow_relation"] = volume_flow_chart
            
            self.logger.info(f"成功生成股票{stock_code}的{len(charts)}个资金流向图表")
            return charts
            
        except Exception as e:
            self.logger.error(f"生成资金流向图表失败: {e}")
            return {"error": f"生成资金流向图表失败: {e}"}
    
    async def _generate_capital_flow_stacked_chart(self, flow_data: Dict[str, Any], stock_code: str) -> Any:
        """生成资金流向堆叠图"""
        try:
            # 提取资金流向数据
            main_inflow = flow_data.get('main_inflow', 0)
            main_outflow = flow_data.get('main_outflow', 0) or abs(main_inflow) if main_inflow < 0 else 0
            retail_inflow = flow_data.get('retail_inflow', 0)
            retail_outflow = flow_data.get('retail_outflow', 0) or abs(retail_inflow) if retail_inflow < 0 else 0
            
            # 准备堆叠图数据
            categories = ['主力资金', '散户资金']
            inflow_values = [
                main_inflow if main_inflow > 0 else 0,
                retail_inflow if retail_inflow > 0 else 0
            ]
            outflow_values = [
                main_outflow if main_outflow > 0 else 0,
                retail_outflow if retail_outflow > 0 else 0
            ]
            
            # 准备资金流向数据
            flow_chart_data = {
                'main_inflow': main_inflow if main_inflow > 0 else 0,
                'main_outflow': main_outflow if main_outflow > 0 else 0,
                'retail_inflow': retail_inflow if retail_inflow > 0 else 0,
                'retail_outflow': retail_outflow if retail_outflow > 0 else 0,
                'other_inflow': 0,
                'other_outflow': 0
            }
            
            # 返回图表数据字典，不调用visualizer
            return {
                'type': 'capital_flow_stacked',
                'stock_code': stock_code,
                'title': f"{stock_code} 资金流向堆叠图",
                'data': flow_chart_data
            }
            
        except Exception as e:
            self.logger.error(f"生成资金流向堆叠图失败: {e}")
            return None
    
    async def _generate_net_flow_trend_chart(self, flow_data: Dict[str, Any], history_data: pd.DataFrame, stock_code: str) -> Any:
        """生成净流入趋势图"""
        try:
            # 计算净流入数据
            main_net = flow_data.get('main_inflow', 0)
            retail_net = flow_data.get('retail_inflow', 0)
            total_net = main_net + retail_net
            
            # 准备趋势数据
            dates = history_data.index[-10:] if len(history_data) > 10 else history_data.index
            prices = history_data['收盘'].iloc[-10:] if len(history_data) > 10 else history_data['收盘']
            
            # 模拟净流入趋势（实际应用中应从历史数据获取）
            net_flow_trend = [total_net * (0.8 + 0.4 * i/10) for i in range(len(dates))]
            
            # 准备价格成交量数据
            price_volume_data = pd.DataFrame({
                '日期': dates,
                '收盘': prices,
                '成交量': [0] * len(dates)  # 净流入趋势图不需要成交量
            })
            
            # 返回图表数据字典，不调用visualizer
            return {
                'type': 'net_flow_trend',
                'stock_code': stock_code,
                'title': f"{stock_code} 净流入趋势图",
                'data': price_volume_data.to_dict('records')
            }
            
        except Exception as e:
            self.logger.error(f"生成净流入趋势图失败: {e}")
            return None
    
    async def _generate_volume_flow_relation_chart(self, flow_data: Dict[str, Any], history_data: pd.DataFrame, stock_code: str) -> Any:
        """生成成交量资金关系图"""
        try:
            # 获取成交量数据
            volumes = history_data['成交量'].iloc[-20:] if len(history_data) > 20 else history_data['成交量']
            dates = history_data.index[-20:] if len(history_data) > 20 else history_data.index
            
            # 模拟资金流向与成交量的关系
            main_flow_ratio = flow_data.get('main_inflow_ratio', 0)
            retail_flow_ratio = flow_data.get('retail_inflow_ratio', 0)
            
            # 准备资金流向数据（模拟历史数据）
            flow_relation_data = {
                'main_inflow': main_flow_ratio * 1000000,  # 转换为金额
                'main_outflow': 0,
                'retail_inflow': retail_flow_ratio * 500000,
                'retail_outflow': 0,
                'other_inflow': 0,
                'other_outflow': 0
            }
            
            # 返回图表数据字典，不调用visualizer
            return {
                'type': 'volume_flow_relation',
                'stock_code': stock_code,
                'title': f"{stock_code} 成交量与资金流向关系图",
                'data': flow_relation_data
            }
            
        except Exception as e:
            self.logger.error(f"生成成交量资金关系图失败: {e}")
            return None

    async def _generate_capital_signals(self, stock_code: str, output_format: str = "text") -> Union[Dict[str, Any], str]:
        """生成资金信号，支持文本和JSON格式输出"""
        try:
            # 根据输出格式返回结果
            if output_format == "json":
                # 获取各项分析数据
                flow_data = await self._analyze_capital_flow(stock_code)
                volume_data = await self._assess_volume_trends(stock_code)
                institutional_participation = await self._evaluate_institutional_participation(stock_code)
                market_sentiment = await self._analyze_market_sentiment_json(stock_code)
                
                # 计算评分和置信度
                capital_score = await self._calculate_capital_score(flow_data, volume_data)
                confidence = self._calculate_capital_confidence(flow_data, volume_data)
                summary = self._generate_capital_summary(capital_score, flow_data, volume_data)
                
                return {
                    "dimension": "capital",
                    "score": capital_score,
                    "analysis": {
                        "capital_flow": {
                            "main_inflow": flow_data.get('main_inflow', 0),
                            "main_inflow_ratio": flow_data.get('main_inflow_ratio', 0),
                            "retail_inflow": flow_data.get('retail_inflow', 0),
                            "retail_inflow_ratio": flow_data.get('retail_inflow_ratio', 0)
                        },
                        "volume_analysis": {
                            "volume_ratio": volume_data.get('volume_ratio', 1.0),
                            "volume_trend": volume_data.get('volume_trend', '未知'),
                            "price_volume_relation": volume_data.get('price_volume_relation', '未知')
                        },
                        "institutional_participation": institutional_participation,
                        "market_sentiment": market_sentiment,
                        "summary": summary
                    },
                    "confidence": confidence,
                    "timestamp": pd.Timestamp.now().isoformat()
                }
            else:
                # 保持向后兼容的文本输出
                return await self._generate_capital_signals_text(stock_code)
                
        except Exception as e:
            error_msg = f"生成资金信号失败: {e}"
            if output_format == "json":
                return {
                    "error": error_msg,
                    "dimension": "capital",
                    "score": 0.0,
                    "analysis": {
                        "capital_flow": {
                            "main_inflow": 0,
                            "main_inflow_ratio": 0,
                            "retail_inflow": 0,
                            "retail_inflow_ratio": 0
                        },
                        "volume_analysis": {
                            "volume_ratio": 1.0,
                            "volume_trend": "未知",
                            "price_volume_relation": "未知"
                        },
                        "institutional_participation": "未知",
                        "market_sentiment": "情绪平稳",
                        "summary": error_msg
                    },
                    "confidence": 0.0,
                    "timestamp": pd.Timestamp.now().isoformat()
                }
            else:
                return error_msg

    async def _analyze_capital_flow(self, stock_code: str) -> Dict[str, Any]:
        """分析资金流向"""
        try:
            flow_data = await stock_data_provider.get_stock_capital_flow(stock_code)
            
            if not flow_data:
                return {
                    "main_inflow": 0,
                    "main_inflow_ratio": 0,
                    "retail_inflow": 0,
                    "retail_inflow_ratio": 0,
                    "error": "无法获取资金流向数据"
                }
                
            return {
                "main_inflow": flow_data.get('main_inflow', 0),
                "main_inflow_ratio": flow_data.get('main_inflow_ratio', 0),
                "retail_inflow": flow_data.get('retail_inflow', 0),
                "retail_inflow_ratio": flow_data.get('retail_inflow_ratio', 0)
            }
            
        except Exception as e:
            return {
                "main_inflow": 0,
                "main_inflow_ratio": 0,
                "retail_inflow": 0,
                "retail_inflow_ratio": 0,
                "error": f"分析资金流向失败: {e}"
            }

    async def _assess_volume_trends(self, stock_code: str) -> Dict[str, Any]:
        """评估成交量趋势"""
        try:
            history_data = await stock_data_provider.get_stock_history_data(stock_code)
            
            if history_data.empty:
                return {
                    "volume_ratio": 1.0,
                    "volume_trend": "未知",
                    "price_volume_relation": "未知",
                    "error": "无法获取成交量数据"
                }
                
            volumes = history_data['成交量']
            prices = history_data['收盘']
            
            # 计算成交量比率
            volume_ma20 = volumes.rolling(20).mean()
            volume_ratio = volumes.iloc[-1] / volume_ma20.iloc[-1] if not volume_ma20.empty else 1.0
            
            # 成交量趋势判断
            if volume_ratio > 1.5:
                volume_trend = "放大"
            elif volume_ratio > 0.8:
                volume_trend = "平稳"
            else:
                volume_trend = "萎缩"
                
            # 量价关系分析
            price_change = (prices.iloc[-1] - prices.iloc[-2]) / prices.iloc[-2] if len(prices) > 1 else 0
            volume_change = (volumes.iloc[-1] - volumes.iloc[-2]) / volumes.iloc[-2] if len(volumes) > 1 else 0
            
            if price_change > 0.03 and volume_change > 0.5:
                price_volume_relation = "价涨量增"
            elif price_change > 0.03 and volume_change < -0.3:
                price_volume_relation = "价涨量缩"
            elif price_change < -0.03 and volume_change > 0.5:
                price_volume_relation = "价跌量增"
            elif price_change < -0.03 and volume_change < -0.3:
                price_volume_relation = "价跌量缩"
            else:
                price_volume_relation = "量价关系一般"
                
            return {
                "volume_ratio": round(volume_ratio, 2),
                "volume_trend": volume_trend,
                "price_volume_relation": price_volume_relation
            }
            
        except Exception as e:
            return {
                "volume_ratio": 1.0,
                "volume_trend": "未知",
                "price_volume_relation": "未知",
                "error": f"评估成交量趋势失败: {e}"
            }

    async def _evaluate_institutional_participation(self, stock_code: str) -> str:
        """评估机构参与度"""
        try:
            flow_data = await stock_data_provider.get_stock_capital_flow(stock_code)
            
            if not flow_data:
                return "未知"
                
            main_inflow_ratio = flow_data.get('main_inflow_ratio', 0)
            
            if main_inflow_ratio > 0.7:
                return "高度参与"
            elif main_inflow_ratio > 0.4:
                return "积极参与"
            elif main_inflow_ratio > 0.1:
                return "适度参与"
            elif main_inflow_ratio > -0.1:
                return "观望中"
            else:
                return "撤离中"
                
        except Exception as e:
            return "未知"

    async def _analyze_market_sentiment_json(self, stock_code: str) -> str:
        """分析市场情绪（JSON格式专用）"""
        try:
            flow_data = await stock_data_provider.get_stock_capital_flow(stock_code)
            history_data = await stock_data_provider.get_stock_history_data(stock_code)
            
            if not flow_data or history_data.empty:
                return "情绪平稳"
                
            main_inflow_ratio = flow_data.get('main_inflow_ratio', 0)
            retail_inflow_ratio = flow_data.get('retail_inflow_ratio', 0)
            
            # 成交量相对强度
            volumes = history_data['成交量']
            volume_ma20 = volumes.rolling(20).mean()
            volume_ratio = volumes.iloc[-1] / volume_ma20.iloc[-1] if not volume_ma20.empty else 1
            
            # 情绪指标计算
            sentiment_score = 0
            
            # 主力资金情绪
            if main_inflow_ratio > 0.5:
                sentiment_score += 40
            elif main_inflow_ratio > 0.2:
                sentiment_score += 20
            elif main_inflow_ratio < -0.2:
                sentiment_score -= 30
            
            # 散户资金情绪
            if retail_inflow_ratio > 0.3:
                sentiment_score += 20
            elif retail_inflow_ratio < -0.3:
                sentiment_score -= 20
            
            # 成交量情绪
            if volume_ratio > 2:
                sentiment_score += 30
            elif volume_ratio > 1.5:
                sentiment_score += 15
            elif volume_ratio < 0.7:
                sentiment_score -= 15
            
            # 情绪判断
            if sentiment_score > 60:
                return "极度乐观"
            elif sentiment_score > 30:
                return "乐观向上"
            elif sentiment_score > -10:
                return "情绪平稳"
            elif sentiment_score > -40:
                return "情绪谨慎"
            else:
                return "极度悲观"
                
        except Exception as e:
            return "情绪平稳"

    async def _calculate_capital_score(self, flow_data: Dict[str, Any], volume_data: Dict[str, Any]) -> float:
        """
        使用大模型计算0-10分的资金面评分
        
        Args:
            flow_data: 资金流向数据
            volume_data: 成交量数据
            
        Returns:
            0-10分的评分
        """
        try:
            # 构建资金分析数据
            analysis_data = await self._prepare_capital_analysis_data(flow_data, volume_data)
            
            # 使用大模型进行评分
            scoring_prompt = self._get_capital_scoring_prompt(analysis_data)
            llm_response = await self.llm.ainvoke(scoring_prompt)
            
            # 解析大模型响应
            scoring_result = self._parse_llm_scoring_response(llm_response)
            
            # 验证并限制评分范围
            score = self._validate_and_clamp_score(scoring_result.get('score', 5))
            
            self.logger.info(f"资金面分析大模型评分结果: {score}/10")
            return score
            
        except Exception as e:
            self.logger.error(f"资金面评分计算失败: {e}")
            return 5.0  # 默认中等评分

    async def _prepare_capital_analysis_data(self, flow_data: Dict[str, Any], volume_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        准备资金面分析数据供大模型使用
        
        Args:
            flow_data: 资金流向数据
            volume_data: 成交量数据
            
        Returns:
            结构化的资金面分析数据
        """
        try:
            analysis_data = {
                "capital_flow": {},
                "volume_analysis": {},
                "market_sentiment": {}
            }
            
            # 资金流向指标
            main_inflow_ratio = flow_data.get('main_inflow_ratio', 0)
            retail_inflow_ratio = flow_data.get('retail_inflow_ratio', 0)
            main_inflow = flow_data.get('main_inflow', 0)
            retail_inflow = flow_data.get('retail_inflow', 0)
            
            analysis_data["capital_flow"]["main_inflow_ratio"] = main_inflow_ratio
            analysis_data["capital_flow"]["retail_inflow_ratio"] = retail_inflow_ratio
            analysis_data["capital_flow"]["main_inflow"] = main_inflow
            analysis_data["capital_flow"]["retail_inflow"] = retail_inflow
            
            # 成交量指标
            volume_ratio = volume_data.get('volume_ratio', 1.0)
            volume_trend = volume_data.get('volume_trend', '未知')
            price_volume_relation = volume_data.get('price_volume_relation', '未知')
            
            analysis_data["volume_analysis"]["volume_ratio"] = volume_ratio
            analysis_data["volume_analysis"]["volume_trend"] = volume_trend
            analysis_data["volume_analysis"]["price_volume_relation"] = price_volume_relation
            
            # 市场情绪指标（简化处理）
            sentiment_score = 0
            if main_inflow_ratio > 0.5:
                sentiment_score += 40
            elif main_inflow_ratio > 0.2:
                sentiment_score += 20
            elif main_inflow_ratio < -0.2:
                sentiment_score -= 30
                
            if retail_inflow_ratio > 0.3:
                sentiment_score += 20
            elif retail_inflow_ratio < -0.3:
                sentiment_score -= 20
                
            if volume_ratio > 2:
                sentiment_score += 30
            elif volume_ratio > 1.5:
                sentiment_score += 15
            elif volume_ratio < 0.7:
                sentiment_score -= 15
                
            analysis_data["market_sentiment"]["sentiment_score"] = sentiment_score
            
            return analysis_data
            
        except Exception as e:
            self.logger.error(f"准备资金面分析数据失败: {e}")
            return {}

    def _get_capital_scoring_prompt(self, analysis_data: Dict[str, Any]) -> str:
        """
        构建资金面分析的大模型评分prompt
        
        Args:
            analysis_data: 资金面分析数据
            
        Returns:
            评分prompt字符串
        """
        prompt = f"""
        你是一个专业的资金分析专家，请基于以下资金流向和成交量数据对股票的资金面进行评分。

        资金面分析数据：
        {analysis_data}

        评分标准（0-10分整数）：
        - 10分：资金面极佳，主力资金大力流入，成交量极度活跃，市场情绪极度乐观
        - 8-9分：资金面优秀，主力资金积极流入，成交量显著放大，市场情绪乐观
        - 6-7分：资金面良好，资金流动正常，成交量平稳，市场情绪稳定
        - 4-5分：资金面一般，存在一定资金分歧，成交量一般，市场情绪谨慎
        - 2-3分：资金面较弱，资金有流出迹象，成交量萎缩，市场情绪悲观
        - 0-1分：资金面极差，大量资金撤离，成交量极度萎缩，市场情绪极度悲观

        请综合考虑以下维度：
        1. 主力资金动向：主力资金流入流出比例和金额
        2. 散户资金行为：散户资金流入流出情况
        3. 成交量分析：成交量相对强度和趋势
        4. 量价关系：价格变化与成交量的配合程度
        5. 市场情绪：基于资金数据的市场情绪指标

        请严格按照以下JSON格式输出：
        {{
            "score": 0-10之间的整数,
            "reasoning": "详细的评分理由，包括各维度的分析",
            "strengths": ["资金优势1", "资金优势2", ...],
            "weaknesses": ["资金劣势1", "资金劣势2", ...]
        }}

        请确保评分是0-10之间的整数，并给出充分的评分理由。
        """
        return prompt

    def _parse_llm_scoring_response(self, llm_response: Any) -> Dict[str, Any]:
        """
        解析大模型评分响应
        
        Args:
            llm_response: 大模型响应
            
        Returns:
            解析后的评分结果
        """
        try:
            import json
            import re
            
            response_text = str(llm_response)
            
            # 尝试提取JSON格式内容
            json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
            if json_match:
                json_str = json_match.group()
                scoring_result = json.loads(json_str)
                
                # 验证必需字段
                if 'score' in scoring_result:
                    return scoring_result
            
            # 如果JSON解析失败，尝试从文本中提取评分
            score_match = re.search(r'"score"\s*:\s*(\d+)', response_text)
            if score_match:
                score = int(score_match.group(1))
                return {
                    "score": score,
                    "reasoning": "从响应中提取的评分",
                    "strengths": [],
                    "weaknesses": []
                }
            
            # 如果都失败，返回默认值
            self.logger.warning("无法解析大模型评分响应，使用默认评分")
            return {
                "score": 5,
                "reasoning": "解析失败，使用默认评分",
                "strengths": [],
                "weaknesses": []
            }
            
        except Exception as e:
            self.logger.error(f"解析大模型评分响应失败: {e}")
            return {
                "score": 5,
                "reasoning": f"解析失败: {e}",
                "strengths": [],
                "weaknesses": []
            }

    def _validate_and_clamp_score(self, score: Union[int, float]) -> int:
        """
        验证并限制评分范围在0-10之间
        
        Args:
            score: 原始评分
            
        Returns:
            验证后的整数评分 (0-10)
        """
        try:
            # 转换为整数
            if isinstance(score, (int, float)):
                clamped_score = max(0, min(10, int(round(score))))
                return clamped_score
            else:
                self.logger.warning(f"评分类型无效: {type(score)}，使用默认评分5")
                return 5
        except Exception as e:
            self.logger.error(f"评分验证失败: {e}")
            return 5

    def _calculate_capital_confidence(self, flow_data: Dict[str, Any], volume_data: Dict[str, Any]) -> float:
        """计算分析置信度（0-1）"""
        confidence = 0.5  # 基础置信度
        
        # 数据完整性加分
        if flow_data.get('main_inflow') is not None:
            confidence += 0.2
        if volume_data.get('volume_ratio') is not None:
            confidence += 0.2
            
        # 数据质量加分
        if not flow_data.get('error') and not volume_data.get('error'):
            confidence += 0.1
            
        return round(min(confidence, 1.0), 2)

    def _generate_capital_summary(self, score: float, flow_data: Dict[str, Any], volume_data: Dict[str, Any]) -> str:
        """生成资金面摘要"""
        main_inflow_ratio = flow_data.get('main_inflow_ratio', 0)
        volume_ratio = volume_data.get('volume_ratio', 1.0)
        
        if score >= 8:
            if main_inflow_ratio > 0.5 and volume_ratio > 1.5:
                return "资金面极佳，主力资金大力流入，成交量极度活跃"
            else:
                return "资金面表现优秀，资金流动积极"
        elif score >= 6:
            if main_inflow_ratio > 0.3:
                return "资金面良好，主力资金积极流入，成交量显著放大"
            else:
                return "资金面平稳，资金流动正常"
        elif score >= 4:
            if main_inflow_ratio < -0.2:
                return "资金面一般，存在一定资金分歧，成交量平稳"
            else:
                return "资金面表现一般，资金流动相对平稳"
        elif score >= 2:
            return "资金面较弱，资金有流出迹象，成交量萎缩"
        else:
            return "资金面极差，大量资金撤离，市场极度冷清"

    async def _generate_capital_signals_text(self, stock_code: str) -> str:
        """生成资金信号文本输出（使用LLM评分，保持向后兼容）"""
        try:
            # 获取分析数据
            flow_data = await self._analyze_capital_flow(stock_code)
            volume_data = await self._assess_volume_trends(stock_code)
            institutional_participation = await self._evaluate_institutional_participation(stock_code)
            market_sentiment = await self._analyze_market_sentiment_json(stock_code)
            
            # 使用LLM计算评分，而非硬编码
            capital_score = await self._calculate_capital_score(flow_data, volume_data)
            confidence = self._calculate_capital_confidence(flow_data, volume_data)
            summary = self._generate_capital_summary(capital_score, flow_data, volume_data)
            
            # 生成信号描述（仅描述，不计算分数）
            signals = []

            # 主力资金信号（仅描述，不计算分数）
            main_inflow_ratio = flow_data.get('main_inflow_ratio', 0)
            retail_inflow_ratio = flow_data.get('retail_inflow_ratio', 0)
            
            if main_inflow_ratio > 0.6:
                signals.append("🚀 主力资金狂买（强烈买入信号）")
            elif main_inflow_ratio > 0.3:
                signals.append("📈 主力资金积极买入")
            elif main_inflow_ratio < -0.4:
                signals.append("⚠️ 主力资金大幅流出（强烈卖出信号）")
            elif main_inflow_ratio < -0.2:
                signals.append("📉 主力资金持续卖出")

            # 散户资金信号（仅描述，不计算分数）
            if retail_inflow_ratio > 0.4:
                signals.append("👥 散户资金蜂拥而入（可能存在投机风险）")
            elif retail_inflow_ratio < -0.3:
                signals.append("😨 散户资金恐慌抛售（市场悲观）")

            # 成交量信号（仅描述，不计算分数）
            volume_trend = volume_data.get('volume_trend', '未知')
            if volume_trend == "放大":
                signals.append("🔥 成交量爆发（关注度极高）")
            elif volume_trend == "萎缩":
                signals.append("❄️ 成交量萎缩（市场冷清）")

            # 机构参与信号（仅描述，不计算分数）
            if institutional_participation == "高度参与":
                signals.append("🏦 机构高度认可")
            elif institutional_participation == "撤离中":
                signals.append("🚫 机构集体撤离")

            # 市场情绪信号（仅描述，不计算分数）
            if market_sentiment == "极度乐观":
                signals.append("🎉 市场情绪极度高涨（注意风险）")
            elif market_sentiment == "极度悲观":
                signals.append("😱 市场恐慌情绪（可能存在机会）")

            result = f"股票{stock_code}资金信号：\n\n"

            for signal in signals:
                result += f"{signal}\n"

            # 使用LLM生成的评分，而非硬编码计算
            result += f"\n📊 资金面综合评分: {capital_score:.1f}/10\n"
            result += f"💹 成交量比率: {volume_data.get('volume_ratio', 1.0):.2f}\n"
            result += f"🏦 机构参与: {institutional_participation}\n"
            result += f"🎭 市场情绪: {market_sentiment}\n"
            result += f"🎯 置信度: {confidence:.1%}\n\n"
            result += f"💡 评估总结: {summary}\n"

            return result

        except Exception as e:
            return f"生成资金信号失败: {e}"


# 全局实例
stock_capital_flow_analysis_agent = StockCapitalFlowAnalysisAgent()